﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Castle.ActiveRecord.Queries;
using SinsenWeb.Helpers;
using SinsenWeb.Helpers.Filters.ControllerFilters;
using SinsenWeb.Models;
using SinsenWeb.Models.ViewDataTypes;

namespace SinsenWeb.Controllers
{
    [AdminAction]
    public class RoleController: BaseController
    {

        public ActionResult Index()
        {
            return RedirectToAction("List");
        }

        public ActionResult List()
        {
            var roleArray = Role.FindAll();
            List<RoleListElement> roles = new List<RoleListElement>();

            foreach(var role in roleArray)
            {
                roles.Add(new RoleListElement
                              {
                                  Role = role,
                                  MemberCount = role.GetMemberCount()
                              });
            }

            ViewData.Model = roles;
            return View();
        }

        public ActionResult New()
        {
            ViewData.Model = new Role();
            return View();
        }

        public ActionResult Edit(int Id)
        {
            ViewData.Model = Role.Find(Id);
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Role Role)
        {
            if (ModelState.IsValid)
            {
                Role.CreateAndFlush();
            }
            return RedirectToAction("List");
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Update(Role Role)
        {
            if(ModelState.IsValid)
            {
                Role.SaveAndFlush();
                MessageHelper.Message("Gruppering ble oppdatert");
            }

            return RedirectToAction("List");
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(int Id)
        {
            var role = Role.Find(Id);
            role.DeleteAndFlush();
            MessageHelper.Message("Gruppering ble slettet");
            return RedirectToAction("List");

        }


    }
}
